package com.tiandang.controller;

import tiandang.core.config.AuthResource;
import tiandang.core.utils.HttpClientUtil;
import tiandang.core.utils.JsonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tiandang.core.model.WXSessionModel;
import tiandang.core.response.CommonReturnType;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WXLoginController {

//  @Autowired
//  private RedisOperator redis;

  @Autowired
  private AuthResource resource;

  @PostMapping("/login")
  public CommonReturnType wxLogin(String code) {

//    System.out.println("wxlogin - code: " + code);

//		https://api.weixin.qq.com/sns/jscode2session?
//				appid=APPID&
//				secret=SECRET&
//				js_code=JSCODE&
//				grant_type=authorization_code

    AuthResource bean = new AuthResource();
    BeanUtils.copyProperties(resource, bean);

    String url = "https://api.weixin.qq.com/sns/jscode2session";
    Map<String, String> param = new HashMap<>();
    param.put("appid", bean.getAppid());
    param.put("secret", bean.getSecret());
    param.put("js_code", code);
    param.put("grant_type", "authorization_code");

    String wxResult = HttpClientUtil.doGet(url, param);
//    System.out.println(wxResult);

    WXSessionModel model = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);

    // 存入session到redis
//    redis.set("user-redis-session:" + model.getOpenid(),
//      model.getSession_key(),
//      1000 * 60 * 30);

    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("openid", model.getOpenid());
    return CommonReturnType.success(resultMap);
  }
}
